package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 员工登录
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();//传过来的用户名
        String password = employeeLoginDTO.getPassword();

        //校验账户是否被锁定
        Object flag = redisTemplate.opsForValue().get("login:lock:" + username);//拿到加锁的key
        if (flag != null) {//不为空，说明此账号已经被加锁
            log.info("账号锁定");
            throw new AccountNotFoundException(MessageConstant.LOGIN_LOCK_ERROR_Message);

        }

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            log.info("查询的员工为空，返回错误信息");
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);//抛出异常，异常里是一个错误定义的一个大类
        }
        //密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());//把password重新赋值，加密里面是数组形式
        //密码判断
        if (!password.equals(employee.getPassword())) {
            //密码错误
            log.info("密码比对错误");

            //记录员工密码错误的标记，并设置有效时间为五分钟
            redisTemplate.opsForValue().set(getKey(username), "-", 5, TimeUnit.MINUTES);
            //获取密码错误的标记，如果标记次数大于等于五，则锁定账户一个小时
            Set keys = redisTemplate.keys("login:error:" + username + ":*");//查询前缀是这样的key
            if (keys != null & keys.size() >= 5) {
                log.info("员工在五分钟内登录，密码错误超过五次，将锁定账号一小时");
                redisTemplate.opsForValue().set("login:lock:" + username, "-", 1, TimeUnit.HOURS);
                throw new AccountLockedException(MessageConstant.LOGIN_LOCK_ERROR);//抛异常
            }

            throw new AccountNotFoundException(MessageConstant.PASSWORD_ERROR);//密码错误
        }
        //账号锁定
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定（账户锁定异常）
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //返回实体对象
        return employee;

    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //补全属性
        Employee employee = new Employee();//先new对象
        //属性拷贝，简化代码，emloyee里没赋值到的再手动补
        BeanUtils.copyProperties(employeeDTO, employee);//把DTO的属性先拷贝进去
        employee.setStatus(StatusConstant.ENABLE);//1
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));//密码加密
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser(BaseContext.getCurrentId());//从ThreadLocal中拿出来，最后回到拦截器层时要删除
//        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insert(employee);
    }

    /**
     * 条件分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        //1.设置分页参数
        //开始分页查询，把查询的页码和每页记录数传给 startPage方法,底层原理是动态拼接sql语句，自动计算limit的数据
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        //2.执行查询
        List<Employee> employeeList= employeeMapper.list(employeePageQueryDTO.getName());
        //3.解析并封装结果
        Page<Employee> page= (Page<Employee>) employeeList;//强转为page类型
        return new PageResult(page.getTotal(),page.getResult());

    }

    /**
     *
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //补全属性
            Employee employee= Employee.builder()
                    .id(id)
                    .status(status)
//                    .updateTime(LocalDateTime.now())
//                    .updateUser(BaseContext.getCurrentId())
                    .build();
            employeeMapper.update(employee);//在之后编辑员工可以用到
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        //employee.setPassword("****");//查询时会显示加密密码，此举是加密密码也不给看
        return employee;
    }

    /**
     * 编辑员工
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee=new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);//直接调mapper的方法
    }

    //拼接redis的key
    private static String getKey(String username) {
        return "login:error:" + username + ":" + RandomStringUtils.randomAlphabetic(5);
    }






   /* @Autowired
    private EmployeeMapper employeeMapper;

    *//**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     *//*
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }*/

}
